# coding=utf-8
# 当出现线上和预上线出现干扰的时候用此脚本恢复
import optparse
import os
import requests
import redis
import json
import sys
import time
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from common.auth import sig
import base64

# production
REDIS_P_UID = 2424
REDIS_P_PASSWD = '3164f9a08b9503af280b697855ed108c'

# staging
REDIS_S_UID = 2441
REDIS_S_PASSWD = '3cdef02081c7495c70ee0c727703eedc'


def access_api(api_url, method, headers=None,
               data=None, printif=None, files=None):
    # 访问api

    if method == "GET":
        # r = requests.get(api_url, params=data, headers=headers,timeout=10)
        r = requests.get(api_url, params=data, headers=headers)
    elif method == "POST":
        r = requests.post(api_url, data=data, headers=headers, files=files)
    elif method == "PUT":
        r = requests.put(api_url, data=data, headers=headers, files=files)
    elif method == "DELETE":
        r = requests.delete(api_url, data=data, headers=headers)

    if printif == 1:
        print "-------- API Start --------"
        print u"API URL--------", api_url
        print u"Headers--------", headers
        print u"data_input------", data
        print u"Method--------", method
        print u"Response-----", r.text
    return r


def instruction():
    print '\n        更新完数据后可使用户重新去点击二维码,此时二维码的地址(CDN地址)将发生变化'
    print ' \t使用规则：\n\
                如果只知道短链(3g-9CV-q),你可以只使用-s参数(其他将不生效),\n\
                如果你只知道用户名(yunsonbai@sohu.com)你可以使用-u参数,则其他不在生效.\n\
        注意: \n\
                sns如果修改了落地页前缀,注意修改profile_url'
    print 'Options:'
    print '         -s,--short_url: the short url like h5RkkE9n'
    print '         -u,--user_id: the user_id yunsonbai@sohu.com\n'


def get_common():
    parser = optparse.OptionParser("usage: %prog [options]")
    parser.add_option(
        "-s", "--short_url", dest="short_url",
        help="the short_url like h5RkkE9n")
    parser.add_option(
        "-u", "--user_id", dest="user_id",
        help="the user_id like yunsonbai@sohu.com")
    (options, args) = parser.parse_args()
    short_url = options.short_url
    user_id = options.user_id
    if not short_url and not user_id:
        instruction()
        exit(0)
    if short_url and user_id:
        print 'only be short_url or user_id!'
        exit(0)
    if short_url:
        parameter = {
            'short_url': short_url,
        }
    else:
        parameter = {
            'user_id': user_id,
        }
    return parameter


def get_redis_conf():
    uid = REDIS_P_UID
    url = "http://sceapi.apps.sohuno.com/api/redis/release?uid={0}".format(uid)
    password = REDIS_P_PASSWD
    r = requests.get(url)
    for data in r.json():
        if data['master'] == 1:
            redis_conf = {
                'host': data['ip'],
                'port': data['port'],
                'db': 1,
                'password': password,
                'socket_timeout': None,
                'encoding': 'utf-8',
                'encoding_errors': 'strict',
            }
            return redis_conf


def get_data(redis_conf, parameter):
    redis_master = redis.Redis(connection_pool=redis.ConnectionPool(
        **redis_conf))
    data = redis_master.get(parameter['short_url'])
    if not data:
        print 'not find the key'
        exit(0)
    data = json.loads(data)
    # 如果原始数据异常可以先保存好主页地址后,直接删掉原始数据
    # redis_master.delete(parameter['short_url'])
    return data


def update_qrode(long_url, icon_url):
    # 为了保证CDN及时更新,顾使其CDN链接有后缀
    # 在这采用请求http://domain/qrcode来重新创建(
    # 请求url时需模拟更换头像动作,最后一次icon为用户的头像)
    api_url = 'http://qrcode.sce.sohuno.com/qrcode/'
    data = build_data(long_url, icon_url)
    method = "GET"
    try:
        r = access_api(api_url=api_url, method=method, data=data)
        if r.json()['status'] != 200:
            print 'faild'
            exit(0)
        data = build_data(long_url, icon_url, need_icon=True)
        r = access_api(api_url=api_url, method=method, data=data)
        if r.json()['status'] == 200:
            print '\n---------------------new qrocde data---------------------'
            print r.json()
            print '---------------------------------------------------------'
            print '\nsucceed\n'
        else:
            print r.json()
    except Exception, e:
        print Exception, e


def build_data(long_url, icon_url, need_icon=False):
    default_icon = 'http://social.bjcnc.scs.sohucs.com/home/avatar.png'
    appid = '10002'
    appkey = 'fe89aaf641349342f53d303cf950327e'
    data = {}
    # data['long_url'] = redis_data['long_url']
    data['long_url'] = long_url
    data["appid"] = appid
    data["flyer"] = str(int(1000 * time.time()))
    if need_icon:
        # data['icon'] = redis_data['icon_url']
        data['icon'] = icon_url
        # 针对没有icon的用户
        if not data['icon']:
            data['icon'] = default_icon
    data_sig = sig(data, appkey)
    data["sig"] = data_sig
    return data


def get_icon(user_id):
    # 如果是user_id,则根据user_id去获取头像
    fields = ['userId', 'avatar']
    data = user_info(user_id, fields=fields)
    return data


def user_info(user_ids, fields=None):
    appid = "860000"
    appkey = 'km&jil*o'
    api_url = "http://sns-api.apps.sohuno.com/v5/users/query"
    method = "GET"
    data = {}
    data['user_id'] = ''
    for user_id in user_ids:
        data['user_id'] = data['user_id'] + user_id + ','
    data['user_id'] = data['user_id'][:-1]
    data['fields'] = ''
    if not fields:
        data['fields'] = 'userId'
    else:
        for field in fields:
            data['fields'] = data['fields'] + field + ','
        if 'userId' not in fields:
            data['fields'] = data['fields'] + 'userId' + ','
        data['fields'] = data['fields'][:-1]
    data["appid"] = appid
    data_sig = sig(data, appkey)
    data["sig"] = data_sig
    r = access_api(api_url=api_url, method=method, data=data)
    data = r.json()
    result = {}
    if data['status'] == 100000:
        data = data['data']['userInfos']
        for i in data:
            result[i['userId']] = {}
            for key in i:
                result[i['userId']][key] = i[key]
    return result

if __name__ == "__main__":
    parameter = get_common()
    redis_conf = get_redis_conf()
    if 'user_id' in parameter:
        profile_url = "http://3g.k.sohu.com/snsj/profile/"
        url = base64.b64encode(parameter['user_id'])
        if "=" in url:
            url = url.replace("=", "-")
        long_url = profile_url + url
        user_id = [parameter['user_id']]
        icon_url = get_icon(user_id)[parameter['user_id']]['avatar']
        update_qrode(long_url, icon_url)

    else:
        redis_data = get_data(redis_conf, parameter)
        update_qrode(redis_data['long_url'], redis_data['icon_url'])
